package com.team.bus.module.dd.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.zjframework.traceframe.common.controller.BaseController;
import org.zjframework.traceframe.common.dao.util.ConfigUtil;
import org.zjframework.traceframe.common.dao.util.StringUtil;
import org.zjframework.traceframe.common.pagemodel.Tree;
import org.zjframework.traceframe.common.util.GetPinyin;
import org.zjframework.traceframe.common.util.JSONUtil;
import org.zjframework.traceframe.common.util.PageHelper;
import com.team.bus.module.common.pagemodel.SessionInfo;
import com.team.bus.module.dd.model.Dd;
import com.team.bus.module.dd.pagemodel.Pdd;
import com.team.bus.module.dd.service.IDdService;

@Controller
@RequestMapping("/dd")
public class DdController extends BaseController {

	@Autowired
	private IDdService ddService;

    /**
	 * @author 赵继
	 * @return
	 * 功能描述：跳转到栏目页列表页
	 */
	@RequestMapping("/dd")
	public String show(){
		return "/dd/dd";
	}

	@RequestMapping(value = "/getTreeMenu")
    public void getTreeMenu(String id,HttpServletRequest request,HttpServletResponse response) {
		List<Dd> menus = new ArrayList<Dd>();
		List<Pdd> pmenus = new ArrayList<Pdd>();
		if(id==null || id.equals("")){
			menus = ddService.findHql("from Dd where dd is null order by orderno");
		}else{
			menus = ddService.findHql("from Dd where dd.id=? order by orderno",id);
		}
		for(Dd m : menus){
			Pdd pm = new Pdd();
			BeanUtils.copyProperties(m, pm);
			if(m.getDds()!=null && !m.getDds().isEmpty()){
				pm.setState("closed");
			}else{
				pm.setState("open");
			}
			pmenus.add(pm);
		}
		super.writeJSON(pmenus,request,response);
    }

	@RequestMapping(value = "/getTree")
	@ResponseBody
    public List<Tree> getTree(SessionInfo sessionInfo,HttpSession session) {
		sessionInfo = (SessionInfo) session.getAttribute(ConfigUtil.getSessionInfoName());
		List<Dd> dds = new ArrayList<Dd>();
		List<Tree> lt = new ArrayList<Tree>();
			dds = ddService.findHql("from Dd order by orderno");

		if(dds!=null){
			for(Dd m : dds){
				Tree tree = new Tree();
				BeanUtils.copyProperties(m, tree);
				if(m.getDd()!=null){
					tree.setPid(m.getDd().getId());
				}

				lt.add(tree);
			}
		}
		return lt;
    }


	/**
	 * @author 赵继
	 * @return
	 * 功能描述：异步加载TreeGrid
	 */
	@RequestMapping("/treegrid")
	public void treegrid(HttpServletRequest request,HttpServletResponse response,PageHelper ph,String id){
		String hql = "";
		Map<String,Object> param = new HashMap<>();
			hql = "from Dd order by orderno";
		List<Dd> smenus = ddService.findHql(hql, param);
		List<Pdd> tmenus = new ArrayList<>();
		Map<String,Object> attributes = new HashMap<>();
		for(Dd s : smenus){
			Pdd m = new Pdd();
			BeanUtils.copyProperties(s, m);
			if(s.getDd()!=null){
				m.setPid(s.getDd().getId());
			}
			if(StringUtil.isNotEmpty(s.getOrderno())){
				attributes.put("orderno", s.getOrderno());
			}
			tmenus.add(m);
		}
		super.writeJSON(tmenus, request, response);
	}


	@RequestMapping("/tree")
	@ResponseBody
	public List<com.team.bus.module.menu.pagemodel.Menu> tree() {
		String hql = "";
		Map<String,Object> param = new HashMap<>();
			hql = "from Dd order by orderno";
		List<Dd> smenus = ddService.findHql(hql, param);
		List<com.team.bus.module.menu.pagemodel.Menu> tmenus = new ArrayList<>();
		Map<String,Object> attributes = new HashMap<>();
		for(Dd s : smenus){
			com.team.bus.module.menu.pagemodel.Menu t = new com.team.bus.module.menu.pagemodel.Menu();
			BeanUtils.copyProperties(s, t);

			if(s.getDd()!=null){
				t.setPid(s.getDd().getId());
			}
			if(StringUtil.isNotEmpty(s.getOrderno())){
				attributes.put("orderno", s.getOrderno());
			}
			t.setAttributes(attributes);
			tmenus.add(t);
		}
		return tmenus;
	}

	@RequestMapping("/reloadTree")
	@ResponseBody
	public List<com.team.bus.module.menu.pagemodel.Menu> reloadTree(String text) {
		String hql = "";
		Map<String,Object> param = new HashMap<>();
		String hql1 = "from Dd where text='"+text+"'";
		List<Dd> smenus1 = ddService.findHql(hql1);
		hql = "from Dd where id='"+smenus1.get(0).getId()+"' or dd.id='"+smenus1.get(0).getId()+"' order by orderno";
		List<Dd> smenus = ddService.findHql(hql, param);
		List<com.team.bus.module.menu.pagemodel.Menu> tmenus = new ArrayList<>();
		Map<String,Object> attributes = new HashMap<>();
		for(Dd s : smenus){
			com.team.bus.module.menu.pagemodel.Menu t = new com.team.bus.module.menu.pagemodel.Menu();
			BeanUtils.copyProperties(s, t);

			if(s.getDd()!=null){
				t.setPid(s.getDd().getId());
			}
			if(StringUtil.isNotEmpty(s.getOrderno())){
				attributes.put("orderno", s.getOrderno());
			}
			t.setAttributes(attributes);
			tmenus.add(t);
		}
		return tmenus;
	}


	/**
	 * @author 赵继
	 */
	@RequestMapping("/addTo")
	public String addTo(){

		return "/dd/ddAdd";
	}


	/**
	 * @author 赵继
	 */
	@RequestMapping("/editTo")
	public String editTo(){

		return "/dd/ddEdit";
	}

	/**
	 * @author 赵继
	 */
	@RequestMapping("/edit")
	public void edit(HttpServletRequest request,HttpServletResponse response,
			Pdd pdd){

		JSONUtil json = new JSONUtil();
		Dd dd = new Dd();
			try {
				if(pdd!=null){
					BeanUtils.copyProperties(pdd, dd);
                    if(StringUtil.isNotEmpty(pdd.getPid())){
                        Dd tmenu1 = ddService.get(Dd.class, pdd.getPid());
                        dd.setDd(tmenu1);
                        if(StringUtil.isNotEmpty(tmenu1.getDd())){
                            dd.setLeavl("3");
                            dd.setData_group(GetPinyin.getPinYinHeadChar(pdd.getText()).substring(0,1).toUpperCase());
                            dd.setData_tags(GetPinyin.getPingYin(pdd.getText()));
                        }else{
                            dd.setData_group(GetPinyin.getPinYinHeadChar(pdd.getText()).substring(0,1).toUpperCase());
                            dd.setData_tags(GetPinyin.getPingYin(pdd.getText()));
                            dd.setLeavl("2");
                        }
                    }else{
                        dd.setLeavl("1");
                    }
					dd = ddService.updateRow(dd);
					json.setSuccess(true);
					pdd.setId(dd.getId());
					if(!StringUtil.isEmpty(dd.getDd().getId())){
						pdd.setPid(dd.getDd().getId());
					}
					json.setObj(pdd);
					json.setMsg("编辑成功！");
				}
			} catch (Exception e) {
				e.printStackTrace();
				json.setMsg(e.getMessage());
			}
		super.writeJSON(json,request,response);
	}


	/**
	 * @author 赵继
	 */
	@RequestMapping("/save")
	public void save(HttpServletRequest request,HttpServletResponse response,
			Pdd pdd){
		JSONUtil json = new JSONUtil();
		Dd dd = new Dd();
			try {
				if(pdd!=null){
					BeanUtils.copyProperties(pdd, dd);
					if(StringUtil.isNotEmpty(pdd.getPid())){
						Dd tmenu1 = ddService.get(Dd.class, pdd.getPid());
						dd.setDd(tmenu1);
                        if(StringUtil.isNotEmpty(tmenu1.getDd())){
                            dd.setLeavl("3");
                            dd.setData_group(GetPinyin.getPinYinHeadChar(pdd.getText()).substring(0,1).toUpperCase());
                            dd.setData_tags(GetPinyin.getPingYin(pdd.getText()));
                        }else{
                            dd.setData_group(GetPinyin.getPinYinHeadChar(pdd.getText()).substring(0,1).toUpperCase());
                            dd.setData_tags(GetPinyin.getPingYin(pdd.getText()));
                            dd.setLeavl("2");
                        }
					}else{
                        dd.setLeavl("1");
                    }
					dd = ddService.saveInsertRow(dd);
					json.setSuccess(true);
					json.setMsg("操作成功");
					pdd.setId(dd.getId());
					if(!dd.getDd().getId().equals("")){
						pdd.setPid(dd.getDd().getId());
					}
					json.setObj(pdd);
				}
			} catch (Exception e) {
				e.printStackTrace();
				json.setMsg(e.getMessage());
			}
		super.writeJSON(json,request,response);
	}

	/**
	 * @author 赵继
	 */
	@RequestMapping("/del")
	public void delete(HttpServletRequest request,HttpServletResponse response,String ids){

		JSONUtil json = new JSONUtil();
		StringBuffer hql = new StringBuffer();
		hql.append("delete Dd where id=");
		hql.append("'"+ids+"'");
		try {
			ddService.executeHql(hql.toString());
			json.setSuccess(true);
			json.setMsg("删除成功");
		} catch (Exception e) {
			e.printStackTrace();
			json.setMsg("删除失败:"+e.getMessage());
		}
		super.writeJSON(json,request,response);
	}

	/**
	 * 获取序号
	 */
	@RequestMapping("/ddorderno")
	@ResponseBody
	public int getSubSize(String id){
		Map<String,Object> param = new HashMap<String,Object>();
		param.put("id", id);
		List<Dd> dds = ddService.findHql("from Dd where dd.id=:id", param);
		return dds.size();
	}

    /**
     * 获取指定节点的,指定leavl的数据字典
     */
    @RequestMapping("/ddLeavl")
    @ResponseBody
    public List<Pdd> getDdLeavel(){
        List<Dd> dds = ddService.findHql("from Dd where leavl='3'");
        List<Pdd> pmenus = new ArrayList<Pdd>();
        for(Dd m : dds){
            Pdd pm = new Pdd();
            BeanUtils.copyProperties(m, pm);
            pmenus.add(pm);
        }
        return pmenus;
    }

}
